package com.docconverter.service;

import com.docconverter.DocToPdfConverter;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class ConversionService {
    private static final String BASE_DIR = "C:\\Users\\gulis\\Desktop";
    private static final String UPLOAD_DIR = "upload_docs";
    private static final String OUTPUT_DIR = "output_pdfs";
    private final Path uploadPath;
    private final Path outputPath;
    private final DocToPdfConverter converter;

    public ConversionService() throws IOException {
        // 使用绝对路径
        this.uploadPath = Paths.get(BASE_DIR, UPLOAD_DIR).toAbsolutePath().normalize();
        this.outputPath = Paths.get(BASE_DIR, OUTPUT_DIR).toAbsolutePath().normalize();
        Files.createDirectories(uploadPath);
        Files.createDirectories(outputPath);
        this.converter = new DocToPdfConverter();
    }

    public String convertFiles(List<MultipartFile> files) throws Exception {
        // 创建临时目录存储上传的文件
        String sessionId = UUID.randomUUID().toString();
        Path sessionDir = uploadPath.resolve(sessionId);
        Files.createDirectories(sessionDir);

        try {
            // 保存上传的文件
            List<File> documents = new ArrayList<>();
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    Path filePath = sessionDir.resolve(file.getOriginalFilename());
                    Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                    documents.add(filePath.toFile());
                }
            }

            // 转换文件
            String outputFileName = converter.convertDocuments(sessionDir.toFile());
            
            // 确保输出文件存在并移动到正确的位置
            Path sourceFile = Paths.get(BASE_DIR, OUTPUT_DIR, outputFileName);
            Path targetFile = outputPath.resolve(outputFileName);
            
            if (Files.exists(sourceFile)) {
                Files.move(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
            }
            
            return outputFileName;

        } finally {
            // 清理临时文件
            deleteDirectory(sessionDir);
        }
    }

    public Resource loadAsResource(String filename) throws IOException {
        try {
            Path file = outputPath.resolve(filename).normalize();
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new RuntimeException("Could not read file: " + filename);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("Could not read file: " + filename, e);
        }
    }

    private void deleteDirectory(Path dir) throws IOException {
        if (Files.exists(dir)) {
            Files.walk(dir)
                .sorted(java.util.Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
        }
    }
} 